package com.cxb;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.amitek.aidl.mqtt.bean.ConfigStatus;
import com.amitek.aidl.mqtt.bean.OtaStatus;
import com.cxb.service.CXBMainService;
import com.cxb.utils.CommonUtils;
import com.cxb.utils.Constants;
import com.cxb.utils.UpdateUtils;
import com.cxb.view.DialogCreater;
import com.cxb.view.DialogCreater.OnDialogOperateListener;

public class SystemUpdateActivity extends BaseActivity implements Callback {

	private Button btnBack;
	private Button btn_update, btn_refrash;
	private ListView lvUpdateList;
	private Handler mHandler;
	private UpdateUtils updateManager;
	private Dialog progressDialog;
	private TextView tv_update_title;
	private TextView tv_current_version;
	private View ll_user_wifi_update;
	private AlertDialog dialog_update_from_sd;
	private DialogCreater dialogCreater;
	private OtaStatus otaStatus;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_system_update);
		btnBack = (Button) findViewById(R.id.bt_back);
		btn_update = (Button) findViewById(R.id.btn_update);
		btn_refrash = (Button) findViewById(R.id.btn_refrash);
		ll_user_wifi_update = findViewById(R.id.ll_user_wifi_update);
		ll_user_wifi_update.setVisibility(View.GONE);
		btn_update.setVisibility(View.GONE);
		tv_update_title = (TextView) findViewById(R.id.tv_update_title);
		tv_current_version = (TextView) findViewById(R.id.tv_current_version);

		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		btn_update.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startUpdate();
			}
		});
		btn_refrash.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				progressDialog = dialogCreater.getLoadingDialog(false,
						getString(R.string.searching_update));
				progressDialog.show();
				OtaStatus otaInfo = null;

				ConfigStatus configStatus = null;
				try {
					configStatus = CXBMainService.getMqttProxy()
							.getConfigStatus();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
				if (configStatus != null) {
					otaInfo = configStatus.otaStatus;
				}
				Message msg = new Message();
				msg.obj = otaInfo;
				mHandler.sendMessage(msg);
			}
		});
		lvUpdateList = (ListView) findViewById(R.id.lv_update_list);
		dialogCreater = new DialogCreater(this);
		mHandler = new Handler(this);
		progressDialog = dialogCreater.getLoadingDialog(false,
				getString(R.string.searching_update));

		progressDialog.show();
		OtaStatus otaInfo = null;

		ConfigStatus configStatus = null;
		try {
			configStatus = CXBMainService.getMqttProxy().getConfigStatus();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		if (configStatus != null) {
			otaInfo = configStatus.otaStatus;
		}
		Message msg = new Message();
		msg.obj = otaInfo;
		mHandler.sendMessage(msg);

		if (UpdateUtils.isSDUpdatePackageExist()) {

			dialog_update_from_sd = new AlertDialog.Builder(this)
					.setMessage(R.string.update_from_sdcard)
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();

								}
							})
					.setPositiveButton(R.string.update,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									UpdateUtils
											.updateFromSdCard(SystemUpdateActivity.this);

								}
							}).create();

			dialog_update_from_sd.show();
		}

	}

	class UpdateListAdapter extends BaseAdapter {

		private List<String> list;

		public UpdateListAdapter(List<String> list) {
			this.list = list;
		}

		@Override
		public int getCount() {
			if (list != null) {
				return list.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			if (list != null) {
				return list.get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {

			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View view;
			if (convertView != null) {
				view = convertView;
			} else {
				view = LayoutInflater.from(SystemUpdateActivity.this).inflate(
						R.layout.update_list_item, null);
			}
			TextView tvContent = (TextView) view.findViewById(R.id.tv_content);
			tvContent.setText((position + 1) + "." + list.get(position));
			return view;
		}

	}

	public String getAppVersion(String versionStr) {

		int versionCode = Integer.parseInt(versionStr.trim());
		int firstCode = (versionCode / 100) % 10 + 1;
		int secondCode = (versionCode / 10) % 10;
		int thirdCode = versionCode % 10;
		return firstCode + "." + secondCode + "." + thirdCode;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
		progressDialog.dismiss();
		setUpdateInfo((OtaStatus) msg.obj);

		return false;
	}

	private void setUpdateInfo(OtaStatus otaStatus) {
		boolean isLastest = false;
		if (otaStatus == null)
			isLastest = true;
		else {

			isLastest = false;
		}

		if (isLastest) {
			btn_update.setVisibility(View.GONE);
			tv_update_title.setText(R.string.not_find_new_version);
			tv_update_title.setVisibility(View.GONE);
			lvUpdateList.setVisibility(View.GONE);
			tv_current_version.setVisibility(View.VISIBLE);
			try {

				tv_current_version.setText(getString(R.string.current_version,
						CommonUtils.getSystemProperties("cxb.software.version")));
				ll_user_wifi_update.setVisibility(View.VISIBLE);
			} catch (Exception e) {

				e.printStackTrace();
			}
		} else {
			lvUpdateList.setVisibility(View.VISIBLE);
			tv_current_version.setVisibility(View.GONE);
			String updateInfo = otaStatus.updateInfo;
			if (updateInfo != null) {
				String[] str = updateInfo.split("\n");
				Set<String> set = new HashSet<String>();
				for (String info : str) {
					if (!TextUtils.isEmpty(info)) {
						set.add(info);
					}
				}
				lvUpdateList.setAdapter(new UpdateListAdapter(
						new ArrayList<String>(set)));
			}
			tv_update_title.setText(R.string.find_new_system_version);
			tv_update_title.setVisibility(View.VISIBLE);
			btn_update.setText(getString(R.string.update));
			btn_update.setVisibility(View.VISIBLE);
			ll_user_wifi_update.setVisibility(View.VISIBLE);
		}

	}

	public void startUpdate() {
		ConfigStatus configStatus = null;
		try {
			configStatus = CXBMainService.getMqttProxy()
					.getConfigStatus();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		if (configStatus != null) {
			otaStatus = configStatus.otaStatus;
		}
		
		if (otaStatus == null) {
			return;
		}
		String size = CommonUtils
				.roundTwo(otaStatus.fileSize / (1024.0 * 1024)) + "MB";
		String askStr = getString(R.string.update_ask, size);

		DialogCreater dc = new DialogCreater(this);
		Dialog alertDialog = dc.getCommonDialog(getString(R.string.prompt),
				askStr, new OnDialogOperateListener() {

					@Override
					public void onConfirm(Dialog dialog) {
						UpdateUtils.startUpdate(SystemUpdateActivity.this,
								otaStatus);
						dialog.dismiss();
					}

					@Override
					public void onCancel(Dialog dialog) {
						dialog.dismiss();
					}
				});
		// CommonUtils.round(value)
		alertDialog.show();
	}


}
